package org.dandsoft.blackbox.knowledge;

import java.io.Serializable;

/**
 * User: dvilyuzhanin
 * Date: 13.01.2009 20:03:14
 */
public class InfoName implements Serializable {
    public final static char PACKAGE_NAME_SPLITER = '.';
    public final static String PACKAGE_NAME_SPLITER_REGX = "[" + PACKAGE_NAME_SPLITER + "]";
    private String packageName;
    private String name;

    public InfoName(InfoName name) {
        this.name = name.getName();
        this.packageName = name.getPackageName();
    }

    public InfoName(String name) {
        if (name == null || name.length() == 0) {
            throw new IllegalArgumentException("Name can not be null or empty");
        }
        int index = 0;
        for (int i = 0; i < name.length(); i++) {
            char ch = name.charAt(i);
            if (PACKAGE_NAME_SPLITER == ch) {
                index = i;
            }
        }
        if (index > 0) {
            init(name.substring(index + 1, name.length()), name.substring(0, index));
        } else {
            init(name, null);
        }
    }

    public InfoName(String name, String packageName) {
        init(name, packageName);
    }

    private void init(String name, String packageName) {
        if (name == null || name.length() == 0) {
            throw new IllegalArgumentException("Name can not be null or empty");
        }

        if (packageName != null && packageName.length() > 0) {
            this.packageName = packageName;
        }
        this.name = name;
    }

    public String[] getPackageNameComponents() {
        if (packageName == null || packageName.length() == 0) {
            return new String[0];
        } else {
            return packageName.split(PACKAGE_NAME_SPLITER_REGX);
        }
    }

    public String getPackageName() {
        return packageName;
    }

    public String getName() {
        return name;
    }

    public String getFullName() {
        if (packageName != null && packageName.length() > 0) {
            return packageName + PACKAGE_NAME_SPLITER + name;
        } else {
            return name;
        }
    }

    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        InfoName infoName = (InfoName) o;

        if (name != null ? !name.equals(infoName.name) : infoName.name != null) return false;
        if (packageName != null ? !packageName.equals(infoName.packageName) : infoName.packageName != null)
            return false;

        return true;
    }

    public int hashCode() {
        int result;
        result = (packageName != null ? packageName.hashCode() : 0);
        result = 31 * result + (name != null ? name.hashCode() : 0);
        return result;
    }
}
